/**
 * @author chenjuan
 * @description 封装一个axios
 */

import axios from 'axios'
//引入Store实例，获取token数据
import Store from '../store'

const Axios = axios.create({
  baseURL: '/apis',
  timeout: 5000
})

//请求前的一个拦截 -如果用户接口需要token才能访问，那一定要有token才能访问
//拦截钩子函数，函数会有一个形参传递过来
Axios.interceptors.request.use(function(config) {
    // config.headers.token = '123'
    // 通过url来进行业务拦截
    let paths = ['/user/validate/code', '/user/app/login']
    if(paths.includes(config.url)) {
        return config
    }else {
        //获取token
        const token = Store.getters['common/token']
        //校验 如果没有token直接返回错误信息
        if(!!token) {
            config.headers.token = token
            return config
        } else {
            return Promise.reject({code:400, message: '你已被拦截,不具备访问权限'})
        }

    }
    // return config
    // return Promise.reject({code:400, message: '你已被拦截'})
})



function Ajax(req) {
  return new Promise((resolve) => {
    Axios.request({
      url: req.url,
      method: req.method || 'POST',
      //  baseURL: '/apis',
      //在请求体中传递参数
      data: req.data || {},
      params: req.params || {},
      //  timeout: 5000
    }).then(({
      data
    }) => {
      resolve(data)
    }).catch(e => {
      console.log(e)
      resolve({
        code: 888,
        message: 'Error in here'
      })
    })
  })

}

export default Ajax
